package org.example.heap;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Java直接内存 = Java堆 + 本地内存
 * Java process memory  = Java heap + native memory
 * 测试直接内存的OOM java.lang.OutOfMemoryError
 * -Xmx20m -XX:MaxDirectMemorySize=10m
 * @author youshang
 * @date 2022/03/25 16:56
 **/
public class MaxDirectMemorySizeTest {

    private static final long _1MB = 1024 * 1024 * 2;

    public static void main(String[] args) {
        Field field = Unsafe.class.getDeclaredFields()[0];
        field.setAccessible(true);

        int num = 0;
        Unsafe unsafe = null;
        try {
            unsafe = (Unsafe)field.get(null);
        while (true){
            unsafe.allocateMemory(_1MB);
            //Thread.sleep(100);
            num++;
        }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            System.out.println(num);
        }
    }

}
